import java.io.*;
import java.net.*;
import java.util.*;

public class UDPClient extends Thread {
	
	private static ArrayList<InetSocketAddress> _SocketAddressList;
	private static Socket _tcpsocket;
	private static byte [] _data = new byte[1024]; 
	private static DatagramSocket _udpsocket;
	private static DatagramPacket _udppacketSend = new DatagramPacket(_data, _data.length);
	private DatagramPacket _udppacketReceive = new DatagramPacket(_data, _data.length); //data is empty when defining packet.
	private static InetSocketAddress _sa = new InetSocketAddress("localhost", 8000);
	
	
	//receive
	public void run(){
			while(!_udpsocket.isClosed()){
	
				try {
					_udpsocket.receive(_udppacketReceive);
				} 
				
				catch (IOException e) {
					e.printStackTrace();
				}
		
					String message = new String (_udppacketReceive.getData(),0,_udppacketReceive.getLength());
					System.out.println("server: "+message); // print packet.
			}
	} 
	
	private static void send(){
		//vars
		boolean quit = false;
		String sentMessage;
		//input handler.
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

			
			while(!quit){
				try {
					sentMessage = reader.readLine();
					_data = sentMessage.getBytes();
					//updates quit.
					quit = (sentMessage.contentEquals("/quit"));
					
					_udppacketSend.setData(_data);
					for(InetSocketAddress addr :_SocketAddressList){
						_udppacketSend.setSocketAddress(addr);
						_udpsocket.send(_udppacketSend); // send packet
					}
					
				} 
				catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

	public static void main(String[] args) {
		Thread receieveThread  = (new UDPClient());
		// pretty stuff.
		System.out.println("======UDP CLIENT======");
	
		try {
			_udpsocket = new DatagramSocket();
			_tcpsocket = new Socket("localhost", 8000);
			ObjectInputStream inputStream = new ObjectInputStream(_tcpsocket.getInputStream());
			_SocketAddressList = (ArrayList<InetSocketAddress>) inputStream.readObject(); //alternative to this is using a static array.
			for(InetSocketAddress addr :_SocketAddressList){
				System.out.println(addr.getAddress());
				System.out.println(addr.getPort());
			}
		} 
		catch (UnknownHostException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}


		receieveThread.start(); //start receiving packet thread.
		send();
		_udpsocket.close();

	}

}
